const mongoose = require('mongoose')
const glob = require('glob')
const path  = require('path')
const dbAddress = 'mongodb://localhost:27017/react-redux'
let connectCount = 0
exports.connectDb = () => {
  function connect() { 
    mongoose.connect(dbAddress, {
      useNewUrlParser: true,
      useCreateIndex: true
    })
  }
  connect()
  mongoose.connection.on('disconnected', () => {
    if (connectCount < 3) {
      connect()
      connectCount+=1
    } else {
      throw new Error('数据库disconnected')
    }
  })
  mongoose.connection.on('error', () => {
    if (connectCount < 3) {
      connect()
      connectCount+=1
    } else {
      throw new Error('数据库error')
    }
  })
  mongoose.connection.once('open', () => {
    console.log('数据库连接成功')
  })
}
exports.initSchema = () => {
  glob.sync(path.resolve(__dirname, './schema/', '**/*.js')).forEach(require)
}